<template>
  <a-drawer
    :title="title"
    placement="right"
    :visible="visible"
    @close="closeModal"
    :width="600"
    :bodyStyle="{ height: 'calc(100% - 110px)' }"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      @finish="onSubmit"
      :model="formState"
      :rules="rules"
    >
      <a-row :gutter="12">
        <a-col :span="24">
          <a-form-item label="关联公司" name="org_branch_id">
            <a-select
              v-model:value="formState.org_branch_id"
              :fieldNames="{
            label: 'company',
            value: 'id',
          }"
              :options="companyList"
              placeholder="请选择关联公司"
              @change="changeCompany"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="收款方单位名称" name="company_name">
            <a-input
              placeholder="请输入收款方单位名称"
              v-model:value="formState.company_name"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="收款人" name="seller_name">
            <a-input
              placeholder="请输入收款人姓名"
              v-model:value="formState.seller_name"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="地址" name="address">
            <a-input
              placeholder="请输入地址"
              v-model:value="formState.address"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="电话" name="phone">
            <a-input placeholder="请输入电话" v-model:value="formState.phone" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="visible">
          <a-form-item label="应用楼宇" name="build_bind">
            <a-alert
              v-if="disabledTree"
              show-icon
              type="warning"
              message="该审批流程原来绑定的项目/楼宇，您未全部选中，无法修改。"
              class="mb-10"
            />
            <ChooseHousingResources
              checkType="build"
              :allDisabled="disabledTree"
              :defaultChecked="{ buildList: checkedBuildList }"
              @request="$utils.commonRequest"
              @getResult="getResult"
              @error="setCheckedError"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <div class="drawer-footer">
        <a-button class="mr-10" @click="closeModal">取消</a-button>
        <a-button type="primary" html-type="submit">保存</a-button>
      </div>
    </a-form>
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  watch,
  toRefs,
} from "vue";
import { message } from "ant-design-vue";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import store from "../../../../store";
import { ChooseHousingResources } from "bl-common-vue3";

export default defineComponent({
  name: "addReceipt",
  components: { ChooseHousingResources },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  setup(props, context) {
    const formRef = ref();
    const formState = reactive({
      seller_name: "",
      address: "",
      phone: "",
      build_bind: [],
      org_branch_id: undefined,
      company_name: "",
    });
    const rules = {
      company_name: [
        {
          required: true,
          message: "请输入收款方单位名称",
        },
      ],
      org_branch_id: [
        {
          required: true,
          message: "请选择关联公司",
        },
      ],
      seller_name: [
        {
          required: true,
          message: "请输入收款人姓名",
        },
      ],
      address: [
        {
          required: false,
        },
      ],
      phone: [
        {
          required: false,
        },
      ],
      build_bind: [
        {
          required: true,
          message: "请选择应用楼宇",
        },
      ],
    };

    const state = reactive({
      checkedBuildList: [],
      disabledTree: false,
      companyList: [],
    });

    /** 选择房源 */
    const setCheckedError = (e) => {
      state.disabledTree = true;
    };
    const getResult = (info) => {
      if (state.disabledTree) {
        return;
      }
      const { villageList, buildList } = info;
      let list = [];
      if (villageList.length) {
        for (let village of villageList) {
          list = [...list, ...village.children];
        }
      }
      if (buildList.length) {
        list = [...list, ...buildList];
      }
      state.checkedBuildList = list;
      const buildData = utils.getProjectBuildByBuildList(
        state.checkedBuildList
      );
      formState.build_bind = {
        villageIds: buildData.villageId,
        buildIds: buildData.buildId,
        room: [],
      };
    };

    const closeModal = () => {
      context.emit("cancel");
      formRef.value.resetFields();
    };

    const onSubmit = () => {
      if (props.id) {
        formState.id = props.id;
        request.put("/org", "/receipt/sellerEdit", formState).then((res) => {
          message.success("修改成功");
          context.emit("success");
        });
        return;
      }
      request.post("/org", "/receipt/sellerAdd", formState).then((res) => {
        message.success("保存成功");
        context.emit("success");
      });
    };

    // 详情
    const sellerEdit = () => {
      request
        .get("/org", "/receipt/sellerDetail", { id: props.id })
        .then((res) => {
          const { detail } = res;
          setModelRef({
            seller_name: detail.seller_name,
            address: detail.address,
            phone: detail.phone,
            org_branch_id: detail.org_branch_id,
            company_name: detail.company_name,
          });
          formState.build_bind = detail.build_bind;
          if (detail.build_bind.buildIds) {
            state.checkedBuildList = detail.build_bind.buildIds.map((id) => ({
              id,
            }));
          }
        });
    };
    const setModelRef = (state) => {
      for (let key in state) {
        formState[key] = state[key];
      }
    };

    const title = computed(() => {
      return props.id ? "编辑收据编号规则" : "新增收据编号规则";
    });

    const changeCompany = (value, option) => {
      formState.address = option?.address || '';
    };

    const getCompanyList = () => {
      return new Promise((resolve) => {
        request
          .get("/org", "/company/orgAndBranch", {})
          .then((res) => {
            state.companyList = res?.list || [];
            if (!props.id) {
              // 新增 -- 默认总公司账户
              let systemData = (res?.list || []).find((v) => v.is_system == 1);
              if (systemData) {
                formState.org_branch_id = systemData.id;
                formState.address = systemData?.address || '';
              }
            }
            resolve();
          });
      });
    };

    const init = () => {
      getCompanyList();
      if (props.id) {
        sellerEdit();
      }
    };

    watch(
      () => props.visible,
      (value) => {
        if (value) {
          init();
        } else {
          formRef.value.resetFields();
          state.checkedBuildList = [];
          state.disabledTree = false;
          state.companyList = [];
        }
      }
    );

    return {
      closeModal,
      onSubmit,
      formRef,
      formState,
      rules,
      title,
      ...toRefs(state),
      setCheckedError,
      getResult,
      changeCompany,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(input::-webkit-outer-spin-button, input::-webkit-inner-spin-button) {
  -webkit-appearance: none;
}

:deep(input[type="number"]) {
  -moz-appearance: textfield;
}
</style>
